import json
import queue
import threading
import time
from queue import Queue
from urllib.parse import quote

import requests
from win10toast_click import ToastNotifier

url_list = 'https://api.shish.cn/flServer/app/indexDownData'
url_detail = 'https://api.shish.cn/flServer/app/getOrderDetail?orderId=%d'
url_detail_pz = 'https://api.shish.cn/flServer/app/getOrderDetailToEvaluate?type=%s&orderId=%d'
url_order = 'https://api.shish.cn/flServer/app/pushQueue?orderId=%d&type=%s&pzStr=%d'
url_pay = 'https://api.shish.cn/flServer/wx/pay/toPayDeposit?userOrderId=30323'

headers = '''
Host: api.shish.cn
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat
content-type: application/json
Referer: https://servicewechat.com/wx395c5585903736a8/29/page-frame.html
Accept-Encoding: gzip, deflate, br
'''


def headers_to_dict(headers):
    if headers is None:
        return None
    """
    将字符串
    '''
    Host: mp.weixin.qq.com
    Connection: keep-alive
    Cache-Control: max-age=
    '''
    转换成字典对象
    {
        "Host": "mp.weixin.qq.com",
        "Connection": "keep-alive",
        "Cache-Control":"max-age="
    }
    :param headers: str
    :return: dict
    """
    headers = headers.split("\n")
    d_headers = dict()
    for h in headers:
        if h:
            k, v = h.split(":", 1)
            d_headers[k] = v.strip()
    return d_headers


# 116.50674045 39.902160899 源创
post = '{"page":%d,"type":"综合","lng":%s,"lat":%s,"categoryId":1}'

# 116.50746335 39.981799646 产业园
# 116.57801617 39.908429378 双柳巷
# 116.4688402  39.9140961   国贸
# 116.4405706，39.9468296   东直门
times = {}

# 提前多少秒开始提示


toast_index = 0


class ToastModel:
    def __init__(self, priority, title, content):
        self.priority = priority
        self.title = title
        self.content = content
        global toast_index
        self.index = toast_index
        toast_index = toast_index + 1

    def __lt__(self, other):
        if self.priority == other.priority:
            return self.index < other.index
        return self.priority < other.priority


class Shi:
    def __init__(self, tag, headers_token, lng, lat, shops, pre_time=10):
        self._tag = tag
        self._headers_token = headers_token
        self._lng = lng
        self._lat = lat
        self._shops = shops
        self._queue = queue.PriorityQueue()
        self.pre_time = pre_time

    def _print(self, s):
        print(self._tag + '->' + str(s))

    def _load(self, page):
        try:
            response = requests.post(url_list, data=(post % (page, self._lng, self._lat)).encode("utf-8"),
                                     headers=headers_to_dict(headers),
                                     verify=False,
                                     timeout=10)
            if response.status_code == 200:
                response_text = response.text
                response.close()
                self._print(response_text)
                records = json.loads(response_text)['data']
                # records = data['records']
                for item in records:
                    sy = item['mtSyNum'] + item['elmSyNum']
                    if sy > 0:
                        t = times.get(item['id'], 0)
                        if t > 10:
                            continue
                        # 秒级时间戳
                        current_time = time.time()
                        today = time.strftime('%Y-%m-%d', time.localtime(current_time))
                        start_time = time.mktime(time.strptime(today + item['startTime'], '%Y-%m-%d%H:%M'))
                        end_time = time.mktime(time.strptime(today + item['endTime'], '%Y-%m-%d%H:%M'))
                        if current_time < start_time - self.pre_time:
                            self._print(
                                '将于：' + item['startTime'] + ' 开始---' + item['shopName'] + '，距离：' + str(
                                    item['distance']))
                            continue
                        # 已过期
                        if current_time > end_time:
                            continue
                        times[item['id']] = t + 1
                        self._addToastToQueue(10, '有可购买的霸王餐',
                                              item['shopName'] + '上新' + '，距离：' + str(item['distance']) + '，剩余' + str(
                                                  sy) + '份，速速抢购！')
                        if current_time >= start_time:
                            self._placeOrder(item)
                if len(records) == 10:
                    self._load(page + 1)
            else:
                response.close()
            del response
        except BaseException as ex:
            self._print(ex)

    def _startToastThread(self):
        toast = ToastNotifier()

        def run():
            while True:
                try:
                    task = self._queue.get(block=True)
                    self._print(task.title + " " + task.content)
                    toast.show_toast(self._tag + '：' + task.title, task.content, icon_path=None, duration=3,
                                     threaded=False)
                    self._queue.task_done()
                except BaseException as e:
                    self._print(e)

        threading.Thread(target=run).start()

    def _addToastToQueue(self, priority, title, content):
        self._queue.put(ToastModel(priority, title, content))

    def _placeOrder(self, item):
        try:
            id = -1
            for s in self._shops:
                if len(s) == 0:
                    continue
                if item['shopName'].find(s) > -1:
                    id = item['id']
                    break
            if id > -1:
                if item['mtSyNum'] > 0:
                    type = '美团'
                else:
                    type = '饿了么'
                # 评价类型
                response = requests.get(url_detail_pz % (quote(type), id), headers=headers_to_dict(headers),
                                        verify=False,
                                        timeout=10)
                if response.status_code == 200:
                    response_text = response.text
                    self._print("取到评价数据，准备下单：" + response_text)
                    json_str = json.loads(response_text)
                    # pz1 无需好评 pz2 五星无图无字 pz3 五星3图20字
                    if json_str['result']['pz1'] > 0:
                        pz = 1
                        pz_str = '无需好评'
                    elif json_str['result']['pz2'] > 0:
                        pz = 2
                        pz_str = '五星无图无字'
                    else:
                        pz = 3
                        pz_str = '五星3图20字'
                    response.close()
                    # 正式下单
                    response = requests.get(url_order % (id, quote(type), pz),
                                            headers=headers_to_dict(self._headers_token),
                                            verify=False,
                                            timeout=10)
                    if response.status_code == 200:
                        response_text = response.text
                        self._print("自动下单：" + response_text)
                        json_str = json.loads(response_text)
                        # if json_str['msg'] == 'success':
                        times[item['id']] = 11
                        self._addToastToQueue(1, '已自动下单，平台：' + type,
                                              '请到' + item['shopName'] + "下再次点击下单并支付！评价类型：" + pz_str)
                    response.close()
                del response
        except BaseException as ex:
            self._print(ex)

    def start(self):
        requests.packages.urllib3.disable_warnings()
        # 增加重试连接次数
        requests.adapters.DEFAULT_RETRIES = 5
        # 关闭多余的连接 requests使用了urllib3库，默认的http connection是keep - alive的，requests设置False关闭。 操作方法:
        s = requests.session()
        s.keep_alive = False
        self._startToastThread()
        self._addToastToQueue(1, '测试', '测试测试测试！')
        while True:
            self._load(1)
            time.sleep(5)
